<script lang="ts" setup>
import { ref, watch } from 'vue'
import type { Column, Pagination } from '../../types/ant'
import type { AttendanceItem, FormData } from '../../types/attendance'
import { ATTENDANCE_COLUMNS } from '../../columns'
import { downloadExcel } from '../../utils/excel'
import { MD_TYPE } from '../../enums/attendance'
import Modal from '@/components/Modal.vue'

const props = withDefaults(
  defineProps<{
    attendanceList?: AttendanceItem[]
    employeeList?: string[]
  }>(),
  {
    attendanceList: () => [],
    employeeList: () => [],
  },
)

// 表单参数
const formData = ref<FormData>({
  employeeName: '',
  hasException: '',
})

// 表格
const page = ref<number>(1)
const list = ref<AttendanceItem[]>([])

watch(
  () => props.attendanceList,
  (val) => {
    list.value = val
  },
  {
    immediate: true,
  },
)

// 查询
function onSearch() {
  page.value = 1

  const { employeeName, hasException } = formData.value

  // 如果都没有输入查询条件，则直接返回所有数据
  if (!employeeName && !hasException) {
    list.value = props.attendanceList
    return
  }
  const parsedHasException = hasException ? JSON.parse(hasException) : null
  // 对数据进行过滤
  const result = props.attendanceList.filter((item: AttendanceItem) => {
    // 根据employeeName筛选
    const matchesEmployeeName = employeeName ? item.employeeName.includes(employeeName) : true
    // 根据hasException筛选
    const matchesHasException = parsedHasException !== null ? item.hasException === parsedHasException : true

    return matchesEmployeeName && matchesHasException
  })

  // 更新过滤后的结果
  list.value = result
}

// 重置
function onReset() {
  formData.value.employeeName = ''
  onSearch()
}

// 切换分页
function onChangeList(pagination: Pagination) {
  page.value = pagination.current
}

// 导出EXCEL某列
const selected = ref<string[]>([
  'customerName',
  'projectName',
  'projectCode',
  'employeeName',
  'workDate',
  'MD',
  'normalDuration',
  'totalOverTimeDay',
  'customerLevel',
  'projectPhase',
  'remark',
  'projectApprovalCode'
])
const selectedList = ref<Column[]>([])

// 导出EXCEL弹窗
const openValue = ref<boolean>(false)

// 切换选择导出EXCEL列
function onChangeSelected(value: string[], option: Column[]) {
  selected.value = value
  selectedList.value = option
}

// 导出EXCEL
function onDownload() {
  // 隐藏弹窗
  openValue.value = false
  // 不选择EXCEL列则导出全部列
  const filterColumns: Column[] = selectedList.value.length > 0 ? selectedList.value : ATTENDANCE_COLUMNS
  // 数据格式处理
  const data = list.value.map((item: AttendanceItem) => {
    const sheet: Record<string, any> = {}
    filterColumns.forEach((column: Column) => {
      sheet[column.title] = item[column.key as keyof AttendanceItem]
    })
    return sheet
  })
  downloadExcel(data, '考勤数据统计')
}
</script>

<template>
  <div class="filter-conatiner">
    <a-form layout="inline">
      <a-form-item label="员工姓名">
        <a-select v-model:value="formData.employeeName" allow-clear show-search>
          <a-select-option v-for="item in employeeList" :key="item" :value="item">
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="考勤异常">
        <a-select v-model:value="formData.hasException" allow-clear show-search>
          <a-select-option value="true">
            有
          </a-select-option>
          <a-select-option value="false">
            无
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>

    <div class="action">
      <a-button type="primary" @click="onSearch">
        查询
      </a-button>
      <a-button @click="onReset">
        重置
      </a-button>
      <a-button type="primary" @click="openValue = true">
        导出EXCEL
      </a-button>
    </div>
  </div>

  <div class="table-container">
    <a-table
      :columns="ATTENDANCE_COLUMNS" :data-source="list" :scroll="{ x: 'max-content' }" :pagination="{
        current: page,
      }" :row-class-name="(record: AttendanceItem) => (record.hasException ? 'red-row' : null)" @change="onChangeList"
    >
      <template #bodyCell="{ text, column }">
        <template v-if="column.key === 'MD' && text">
          <a-tag :color="text === MD_TYPE.N1 ? 'green' : 'blue'">
            {{ text }}
          </a-tag>
        </template>
      </template>
    </a-table>
  </div>

  <!-- 导出EXCEL -->
  <Modal v-model:open="openValue" title="导出EXCEL" @confirm="onDownload">
    <a-select
      v-model:value="selected" mode="tags" placeholder="请选择需要导出EXCEL列, 如不选择EXCEL列则导出全部列"
      :options="ATTENDANCE_COLUMNS" :field-names="{
        label: 'title',
        value: 'key',
      }" @change="onChangeSelected"
    />
  </Modal>
</template>

<style lang="scss" scoped>
.filter-conatiner {
  display: flex;
  align-items: center;
  margin: 8px 0 24px;

  .ant-select {
    width: 200px;
  }

  .ant-btn {
    margin-left: 16px;
  }
}

.table-container {
  :deep(.red-row) {
    color: #f5222d;
  }
}
</style>
